package com.willfe.TreeDroid;

import com.willfe.TreeDroid.TreeDroidDbAdapter;

import android.app.ListActivity;
import android.widget.ListView;
import android.widget.TextView;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SimpleCursorAdapter;

public class TreeDroid extends ListActivity {
	public static final int INSERT_ID = Menu.FIRST;
	private int mTreeNumber = 1;
	private TreeDroidDbAdapter mDbHelper;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        
        setContentView(R.layout.main);
        mDbHelper = new TreeDroidDbAdapter(this);
        mDbHelper.open();
        fillTrees();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	boolean result = super.onCreateOptionsMenu(menu);
        MenuItem add = menu.add(0, INSERT_ID, 0, R.string.menu_insert);
        add.setIcon(R.drawable.treedroidtree);
        MenuItem settings = menu.add(0, 1, 0, R.string.menu_settings);
        settings.setIcon(android.R.drawable.ic_menu_preferences);
        return result;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
      	switch (item.getItemId()) {
        case INSERT_ID:
            createTree();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void createTree() {
        String treeName = "A new tree, #" + mTreeNumber++;
        mDbHelper.createTree(treeName);
        fillTrees();
    }

    private void fillTrees() {
        // Get all of the trees from the database and create the item list
        Cursor c = mDbHelper.fetchTrees();
        startManagingCursor(c);

        String[] from = new String[] { TreeDroidDbAdapter.KEY_TREE_NAME };
        int[] to = new int[] { R.id.text1 };
        
        // Now create an array adapter and set it to display using our row
        SimpleCursorAdapter notes =
            new SimpleCursorAdapter(this, R.layout.main_row, c, from, to);

        setListAdapter(notes);
    }    
}